﻿using System;
using Microsoft.VisualBasic.ApplicationServices;
using System.Linq;
using System.IO;
using System.IO.MemoryMappedFiles;

namespace ArmoryViewer
{
    public sealed class Program : WindowsFormsApplicationBase
    {
        [STAThread]
        public static void Main(string[] args)
        {
            (new Program()).Run(args);
        }
        public Program()
        {
            IsSingleInstance = !IsMultiInstance();
        }

        public App App { get; private set; }

        bool IsMultiInstance()
        {
            try
            {
                using (MemoryMappedFile file = MemoryMappedFile.OpenExisting("multi"))
                {
                    using (MemoryMappedViewStream stream = file.CreateViewStream())
                    {
                        BinaryReader reader = new BinaryReader(stream);
                        return reader.ReadString() == "true";
                    }
                }
            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }

        

        protected override bool OnStartup(StartupEventArgs eventArgs)
        {
            App = new App(this);
            App.Run();
            App.SetMultiInstance(false);
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            base.OnStartupNextInstance(eventArgs);
            App.MainWindow.Activate();
            App.ProcessArgs(eventArgs.CommandLine.ToArray(), false);
        }
    }
}
